import time
import random
import requests
from fake_useragent import UserAgent
import json
import logging
from kuaipai import KuaiPai
# import os
# import sys

logger = logging.getLogger(__name__)
fh = logging.FileHandler('kuaipai.log')
sh = logging.StreamHandler()
logger.addHandler(fh)
logger.addHandler(sh)
logger.setLevel(logging.DEBUG)

headers = {
        'User-Agent': UserAgent().random,
    }

def time_ge():
    with open(r'time_ge.txt','r') as f:
        con = f.read()
    return  con.split(',')
# print(len(time_ge()))
# 提取代理API接口，获取1个代理IP
api_url = "https://dps.kdlapi.com/api/getdps/?orderid=969446626073773&num=20&pt=1&format=json&sep=1"
# time_list = [60*60*1.72,60*60,60*60*2.8,5600,60*5,60*60*0.5,60*60*1.5,60*5,60*20,60*60*0.3,60*60*0.8,60*60*1.3,80]
# print(len(time_list))
def run_kuaipai(keyword,url_host,xiongzhanghao):
    a = 0
    shu = random.randint(8, 13)
    while True:
        time_now = time.strftime("%H", time.localtime())
        if time_now == '08':
            while a <=  shu:
                #ip访问间隔
                time_list = time_ge()
                second = random.choice(time_list)
                time.sleep(second)
                time_list.remove(second)
                # 获取API接口返回的代理IP
                proxy_ip_s = requests.get(api_url).text
                proxy_list = json.loads(proxy_ip_s)['data']['proxy_list']
                ip_port = random.choice(proxy_list)
                #验证ip的可用性
                proxies = {"http": "http://" + ip_port, "https": "https://" + ip_port}
                try:
                    resp = requests.get('https://www.baidu.com',headers=headers,proxies=proxies)#,proxies=proxies
                    if resp.status_code != 200:
                        raise Exception('ip访问失败！')
                except Exception:
                    logger.info('{}--此ip不可用'.format(ip_port))
                    continue
                try:
                    KuaiPai(ip_port,keyword).run(url_host,xiongzhanghao)
                    a += 1
                except:
                    logger.info('{}--ip访问失败'.format(ip_port))
                    continue
        time.sleep(60*10)
run_kuaipai('西红柿的功效与作用','www.zhms.cn','九州醉')